package com.xixibaby.core;

import lombok.Getter;
import lombok.Setter;

import java.util.stream.Stream;

/**
 * @Auther: tomj
 * @Date: 2019-03-01 09:49
 * @Description:
 *
 * 4个参数  1  要连的表（从表targetTable）
 *          2 要连的表的字段 （targetProperty）
 *          3 主表（不存在就用主表）
 *          4 相关的字段主表字段（property）
 *
 * select 主表,从表.name as BrandName from 主表 left join 从表 on 主表.brand_id = 从表.id
 *
 * Join.join("从表").main("主表").onEq("brand_id","id").select("name as BrandName");
 * Join.join().onEq().select("");
 */
@Setter
@Getter
public class Join {

    private String targetTable;
    private String targetProperty;

    private String property;
    private String table;

    /**
     * 1 inner 2 left
     */
    private String joinType ="INNER";

    public Join left(){
        this.joinType = "LEFT";
        return this;
    }

    public String getJoinType() {
        return joinType;
    }

    public Join inner(){
        this.joinType = "INNER";
        return this;
    }

    public String getTable() {
        return table;
    }

    public Join main(String tableName){
        this.table = tableName;
        return this;
    }


    public static Join join(String tableName){
        Join join = new Join();
        join.targetTable = tableName;
        return join;
    }

    public Join onEq(String mainField, String joinField){
        this.property = mainField;
        this.targetProperty = joinField;
        return this;
    }
    public Join select(String... slaveSelectFields){
        select(true,slaveSelectFields);
        return this;
    }

    public Join select(boolean hasTable, String... slaveSelectFields){
        if(hasTable){
            this.targetFields = Stream.of(slaveSelectFields).map(fi -> targetTable + "." + fi).toArray(String[]::new);
        }else{
            this.targetFields = slaveSelectFields;
        }
        return this;
    }



    //连接表要查询的字段

    private String[] targetFields;

}
